package com.leehom.arch.storage;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
 
/**
 * 文件MD5计算工具
 */
public class FileUtils {
	
	public static final String MD5  = "MD5";
    public static final String SHA1 = "SHA-1";

    public static final int bufferSize = 8192;
    
    public static String checkFileMd5(InputStream is) throws IOException {
    	return doCheckFile(is, MD5);
    } 
    
    public static String checkFileSHA1(InputStream is) throws IOException {
    	return doCheckFile(is, SHA1);
    } 

	public static String contactPath(String left, String right) {
		String seq = left.endsWith("/") || left.endsWith("\\") ? "" : File.separator;
		return left + seq + right;
	}
	
    private static String doCheckFile(InputStream is, String hashType) throws IOException {
		try {
			MessageDigest MD5 = MessageDigest.getInstance(hashType);
	        byte[] buffer = new byte[bufferSize];
	        int length;
	        while ((length = is.read(buffer)) != -1) {
	            MD5.update(buffer, 0, length);
	        }
	        return new String(Hex.encodeHex(MD5.digest()));
		} catch (NoSuchAlgorithmException e) {
			// 确保不会出现的异常
			return "";
		}

    } 
}